package com.gitee.apanlh.web.wrapper;

import com.gitee.apanlh.util.encode.StrEncodeUtils;
import com.gitee.apanlh.util.io.IOUtils;
import com.gitee.apanlh.web.util.ServletUtils;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

/**	
 * 	XSSFilter包装类
 *
 * 	@author Pan
 */
public class BaseXssRequestWrapper extends HttpServletRequestWrapper {
	
	private byte[] requestBody;
	
	/**	
	 * 	构造函数
	 * 	<br>不会关闭HttpServletRequest中的读取输入流
	 * 	
	 * 	@author Pan
	 * 	@param  request	HttpServletRequest
	 */
	public BaseXssRequestWrapper(HttpServletRequest request) {
		super(request);

		String read = ServletUtils.readBodyString(request, false);
		this.requestBody = read.getBytes(StandardCharsets.UTF_8);
	}
	
	@Override
	public ServletInputStream getInputStream() {
		final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
		
		return new ServletInputStream() {
			@Override
			public int read() {
				return bais.read();
			}
			@Override
			public void setReadListener(ReadListener listener) {
				// NOOP
			}
			@Override
			public boolean isReady() {
				return false;
			}
			@Override
			public boolean isFinished() {
				return false;
			}
		};
	}
	
	@Override
	public BufferedReader getReader() {
		return IOUtils.getReaderUtf8(getInputStream());
	}
	
	public String getBody() {
		return StrEncodeUtils.utf8EncodeToStr(this.requestBody);
	}
}
